﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace LazyMapper.Core.Helpers
{
    public static class ReflectionHelper
    {
        public static Type DetermineEnumerableType<T>()
        {
            var inputMemberType = typeof(T);
            return  DetermineEnumerableType(inputMemberType);
        }

        public static Type DetermineEnumerableType(Type inputMemberType)
        {
            if (inputMemberType.IsGenericType && inputMemberType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) return inputMemberType.GetGenericArguments()[0];

            if (inputMemberType.IsArray) return inputMemberType.GetElementType();

            var type = inputMemberType.GetInterfaces().Where(i => (i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>))).Select(x => x.GetGenericTypeDefinition()).FirstOrDefault();
            if (type != null) return inputMemberType.GetGenericArguments()[0];

            type = inputMemberType.GetInterfaces().Where(i => (i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICollection<>))).Select(x => x.GetGenericTypeDefinition()).FirstOrDefault();
            if (type != null) return inputMemberType.GetGenericArguments()[0];


            type = inputMemberType.GetInterfaces().Where(i => (i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>))).Select(x => x.GetGenericTypeDefinition()).FirstOrDefault();
            if (type != null) return inputMemberType.GetGenericArguments()[0];

            return null;
        }
    }
}